<template>
  <el-select
    v-model="baseParamStore.baseParam.rearerId"
    value-key="value"
    @change="changeRearer"
    clearable
    placeholder="请选择养户"
    filterable
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      @click.native="changeRearer(item)"
    />
  </el-select>
</template>

<script setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { getRearerListByOrgId } from '@/api/api'
import { useRoute, useRouter } from 'vue-router'
import { useBaseParamStore } from '@/stores/baseParams'

const baseParamStore = useBaseParamStore()
const router = useRouter()
const route = useRoute()
const options = ref()

const fetchRearerListByOrgId = async () => {
  try {
    const res = await getRearerListByOrgId({
      orgId: route.query.orgId
    })
    if (res && res.data) {
      options.value = res.data.map((item) => {
        return {
          value: item.rearerId,
          label: item.orgName + '/' + item.rearerName,
          cqRearerId: item.cqRearerId
        }
      })
    }
  } catch (error) {
    console.error('获取获取告警详情信息失败:', error)
  }
}
const changeRearer = (e) => {
  baseParamStore.baseParam.rearerId = e.value

  // 构造新的查询参数对象
  const newQuery = {
    ...route.query,
    rearerId: e.value, // 替换或新增 rearerId 参数
    farmerId: e.cqRearerId
  }

  // 使用 router.replace 更新地址栏，不触发页面刷新
  router.replace({
    path: route.path,
    query: newQuery
  })
  setTimeout(() => {
    location.reload()
  }, 100)
}

onMounted(() => {
  baseParamStore.baseParam.rearerId = decodeURIComponent(route.query.rearerId)
  fetchRearerListByOrgId()
})
</script>
<style>
.select-company {
  width: 300px;
}
</style>
